//
//  HJAddFriendController.m
//  KaiChat
//
//  Created by lx on 2023/10/21.
//

#import "HJAddFriendController.h"
#import "QMUITextField.h"
#import "TJEmptyDataHandler.h"
#import "HJAddFriendCell.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "HJSearchView.h"

@interface HJAddFriendController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, weak) QMUITextField *textField;


@end

@implementation HJAddFriendController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"Add Friends";
    self.navigationBar.lineView.hidden = YES;

    UIView *headerView = [UIView addToView:self.view];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.height.offset(60);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];

    searchView.textField.placeholder = @"UID or Email";
    searchView.textField.maximumTextLength = 30;
    searchView.textField.returnKeyType = UIReturnKeySearch;
    searchView.textField.delegate = self;
    _textField = searchView.textField;

    _emptyDataHandler =  [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.iconName = @"search_empty";
        dataModel.text = @"Results not found";
        return TJEmptyDataTypeBase;
    }];
    
    
    UILabel *tipLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(13) color:UIColor.tj_868391Color title:@"Search not case sensitive" textAlignment:NSTextAlignmentLeft];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchView);
        make.top.equalTo(searchView.mas_bottom).inset(8);
    }];
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJAddFriendCell.class forCellReuseIdentifier:@"HJAddFriendCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 70;
    self.tableView.backgroundColor = UIColor.whiteColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLabel.mas_bottom).offset(8);
        make.left.right.bottom.offset(0);
    }];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleApplyFridendAgreeNotification) name:applyFridendAgreeNotification object:nil];
    
    dispatch_async_main_queue(^{
        [self.textField becomeFirstResponder];
    });
}

- (void)handleApplyFridendAgreeNotification {
    HJChatUserModel *model = self.datas.firstObject;
    if (!model) {
        return;
    }
    [self searchFriendWithKeyword:model.uid];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJAddFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJAddFriendCell" forIndexPath:indexPath];
    HJChatUserModel *model = self.datas[indexPath.row];
    cell.model = model;
    TJWeakify(self);
    [cell setDidClickAddButtonBlock:^{
        [HJIM.shareIM.userManager sendApplyAddFriendWithUserId:model.userId complete:^(NSError * _Nullable error) {
            [HJIM.shareIM.userManager loadApplyCountComplete:nil];
            model.relationship = 2;
            model.way = 1;
            [weakself.tableView reloadData];
        }];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJChatUserModel *model = self.datas[indexPath.row];
    HJUserInfoController *infoController = [[HJUserInfoController alloc] init];
    infoController.userId = model.userId;
    TJWeakify(self)
    [infoController setApplySucceed:^{
        model.relationship = 2;
        model.way = 1;
        [weakself.tableView reloadData];
    }];
    [self.navigationController pushViewController:infoController];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self didClickSearchButton];
    return YES;
}

- (void)didClickSearchButton {
    if (isEmptyString(_textField.text)) {
        [HJHUD showErrorMessage:_textField.placeholder];
        return;
    }
    [HJHUD showLoadingInView:self.view];
    [self searchFriendWithKeyword:_textField.text];
}

- (void)searchFriendWithKeyword:(NSString *)keyword {
    [HJIM.shareIM.userManager searchFridendWithKeyword:keyword complete:^(HJChatUserModel * _Nullable model) {
        if (model) {
            self.datas = @[model];
        } else {
            self.datas = nil;
        }
        self.emptyDataHandler.canDisplay = YES;
        [self.tableView reloadData];
    }];
    
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}
 
- (void)dealloc {
    if (self.popBlock) {
        self.popBlock();
    }
    NSLog(@"%s", __func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
 
@end
